<?php 
namespace Admin\Logic;
use Think\Model;
class RegionLogic extends Model{

	public $region; 			//所有
	public $firstRegion;		//一级
	public $secondRegion;		//二级

	public function _initialize()
	{
		$this->region = S('region');
		$this->firstRegion = S('firstRegion');
		$this->secondRegion = S('secondRegion');
	}


	/**
	 * [update_cache 缓存]
	 * @return [type] [description]
	 */
	public function update_cache()
	{
		$data = $this->order('region_id asc')->select();

		$region = array();
		$firstRegion = array();
		$secondRetion = array();
		foreach ($data as $k => $v)
		 {
			$region[$v['region_id']]= $v;

			if($v['parent_id']==1)
			{
				$firstRegion[$v['region_id']]= $v;
			}
		}
	
		S('region',$region);
		S('firstRegion',$firstRegion);

		$regionIds = array();
		foreach($firstRegion as $k=> $v)
		{
			$regionIds[] = $v['region_id'];
		}


		$data = $this->where(array('parent_id'=>array('in',$regionIds)))->select();
	
		foreach($data as $k=> $v)
		{
			$secondRegion[$v['region_id']] = $v;
		}

		S('secondRegion',$secondRegion);
	}

	/**
	 * [get_region 获取当前]
	 * @param  [type] $regionId [description]
	 * @return [type]           [description]
	 */
	public function get_region($regionId)
	{
		$firstRegion = array();  	//当前顶级
		$secondRegion = array();	//当前二级
		$thirdRegion = array();		//当前三级


		if(isset($this->firstRegion[$regionId]))
		{
			$firstRegion = $this->firstRegion[$regionId];
		}

		elseif(isset($this->secondRegion[$regionId]))
		{
	
			$secondRegion = $this->secondRegion[$regionId];
			$firstRegion = $this->firstRegion[$secondRegion['parent_id']];
		}

		elseif(isset($this->region[$regionId]))
		{
			$thirdRegion = $this->region[$regionId];
			$secondRegion = $this->secondRegion[$thirdRegion['parent_id']];
			$firstRegion = $this->firstRegion[$secondRegion['parent_id']];
		}
		return array('firstRegion'=>$firstRegion,'secondRegion'=>$secondRegion,'thirdRegion'=>$thirdRegion);
	}

	/**
	 * [get_child_region 获取子集]
	 * @param  [type] $regionId [description]
	 * @return [type]           [description]
	 */
	public function get_child_region($regionId)
	{
		$child = array();
		foreach ($this->region as $v) 
		{
			if($v['parent_id']==$regionId)
			{
				$child[$v['region_id']]=$v;
			}
		}
		return $child;
	}

	/**
	 * [get_same_region 获取同级]
	 * @param  [type] $region [description]
	 * @return [type]         [description]
	 */
	public function get_same_region($region)
	{
		$same = array();
		foreach ($this->region as $v) 
		{
			if($v['parent_id']==$region['parent_id'])
			{
				$same[$v['region_id']]=$v;
			}
		}

		return $same;
	}


	/**
	 * [get_child_all 所有子regionId]
	 * @param  [type] $regionId [description]
	 * @return [type]           [description]
	 */
	public function get_child_all($regionId)
	{
		import('ORG.Util.Data');
		$data =Data::channelList($this->region,$regionId,'','region_id','parent_id');
		$result = array($cid);
		foreach($data as $v)
		{
			$result[]= $v['region_id'];
		}
		return $result;
	}
}





 ?>